/**
 * Copyright (c) 2007, Blue Hole Software. All rights reserved.
 * Code licensed under the Apache 2.0 License:
 * http://www.apache.org/licenses/
 */
package org.bhf.security.common;

import javax.security.auth.Subject;
import java.io.Serializable;
import java.util.Locale;
import java.util.Set;
import java.util.TimeZone;

/**
 * Public credential to carry the user's default locale and time zone.
 */
public final class Location implements Serializable
{
    private static final long               serialVersionUID    = 7930732926638008763L;
    private static final Class<Location>    THIS_CLASS          = Location.class;

    private final Locale    locale;
    private final TimeZone  timezone;

    /**
     * Create a <code>Location</code> credential.
     * @param locale    Must not be <code>null</code>.
     * @param timezone  Must not be <code>null</code>.
     */
    public Location( final Locale locale, final TimeZone timezone )
    {
        assert locale != null;
        assert timezone != null;
        
        this.locale     = locale;
        this.timezone   = timezone;
    }

    /**
     * Get the user's default <code>Locale</code>.
     * @return Will not be <code>null</code>.
     */
    public Locale   getLocale()
    {
        return locale;
    }

    /**
     * Return the user's default <code>TimeZone</code>.
     * @return Will not be <code>null</code>.
     */
    public TimeZone getTimezone()
    {
        return timezone;
    }

    /**
     * Convenience method to return the <code>Location</code> in a
     * <code>Subject</code>.
     *
     * @param subject The <code>Subject</code> from which to extract the
     *      <code>Location</code>.  Must not be <code>null</code>.
     *
     * @return The <code>Location</code> of the given <code>Subject</code>
     * @throws IllegalArgumentException if <code>subject == null</code>
     *      or if <code>subject</code> does not contain exactly one
     *      <code>FullName</code> as a public credential.
     */
    public static Location      getLocation( Subject subject )
    {
        Set<Location> set = subject.getPublicCredentials( THIS_CLASS );

        if( set.size() != 1 )
            throw new IllegalArgumentException( "subject.getPublicCredentials( FullName.class ).size() != 1" );

        return set.iterator().next();
    }

    /**
     * Convenience method to return the <code>Location</code> of the
     * <code>Subject</code> associated with the current thread.
     *
     * @return The <code>Location</code> of the contextual <code>Subject</code>
     * @throws IllegalArgumentException if <code>subject</code> does not
     *      contain exactly one <code>Location</code> as a public credential
     *      or if there is no code>Subject</code> associated with the
     *      current thread.
     */
    public static Location      getLocation()
    {

        return getLocation( ContextSubject.getContextSubject() );
    }
}


